package com.ushio.commonmodule.utils;

import com.ushio.commonmodule.pojo.result.Result;
import com.ushio.commonmodule.pojo.result.ResultCode;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 只处理返回类型是 Result 的响应
        return Result.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  org.springframework.http.MediaType contentType,
                                  Class converterType,
                                  org.springframework.http.server.ServerHttpRequest request,
                                  ServerHttpResponse response) {

        if (!(body instanceof Result<?> result)) {
            return body;
        }

        // 根据 Result.code 映射 HTTP 状态码
        HttpStatus status = switch (result.getCode()) {
            case 200 -> HttpStatus.OK;
            case 401 -> HttpStatus.UNAUTHORIZED;
            case 403 -> HttpStatus.FORBIDDEN;
            case 404 -> HttpStatus.NOT_FOUND;
            case 503 -> HttpStatus.SERVICE_UNAVAILABLE;
            case 500 -> HttpStatus.INTERNAL_SERVER_ERROR;
            default -> HttpStatus.BAD_REQUEST;
        };

        if (response instanceof ServletServerHttpResponse servletResponse) {
            servletResponse.setStatusCode(status);
        }

        return result;
    }
}
